<?php

namespace App\Http\Controllers;

use App\Models\TagData;
use Barryvdh\Reflection\DocBlock\Tag\AuthorTag;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;


class TagController extends Controller
{
    /**
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Contracts\View\Factory|\Illuminate\Http\JsonResponse|\Illuminate\View\View|\Symfony\Component\HttpFoundation\Response
     */
    public function index()
    {
        if ($this->isPost()) {
            $where          = '1';
            $category       = $this->request->input('category');
            $category_child = $this->request->input('category_child');
            $content        = $this->request->input('content');
            if (intval($category) > 0) {
                $where .= sprintf(' and category_id=%s', $category);
            }
            if (intval($category_child) > 0) {
                $where .= sprintf(' and category_child_id=%s', $category_child);
            }
            if (!empty($content)) {
                $where .= sprintf(' and instr(tag_name, "%s")', $content);
            }


            $list    = TagData::orderBy('tag_id', 'desc')
                ->whereRaw($where)
                ->paginate($this->request->input('limit'));

            $listArr = $list->toArray();
            $data    = $listArr['data'];
            $result  = [];
            if ($data) {
                foreach ($data as $item) {
                    $tmp                = [];
                    $unJson             = json_decode($item['data'], true);
                    $tmp['tag_id']      = $item['tag_id'];
                    $tmp['tag_defined'] = sprintf("标签名称：%s<br/>定义者：%s<br/>标签口径：%s",
                        $unJson['tag_name'], $unJson['defined_name'], $unJson['tag_size']);
                    $tmp['tag_base']    = sprintf("标签分类：%s<br/>定义部门 ：%s<br/>标签状态：%s<br/>开放权限:%s<br/>备注:%s<br/>",
                        TagData::getCategoryMix($unJson['category'], $unJson['category_child']),
                        TagData::changeType('department', $unJson['defined_department']),
                        $unJson['tag_size'],
                        TagData::changeType('state', $unJson['tag_state']),
                        TagData::changeType('auth', $unJson['open_auth']),
                        $unJson['remark']
                    );
                    $tmp['tag_save']    = sprintf("列名：%s<br/>标签类型：%s<br/>标签精度：%s<br/>标签值单位：%s<br/>标签物理类型：%s<br/>表名:%s<br/>",
                        $unJson['column_name'],
                        TagData::changeType('type', $unJson['tag_type']),
                        $unJson['tag_precision'],
                        TagData::changeType('unit', $unJson['tag_unit']),
                        TagData::changeType('physics', $unJson['tag_physics_type']),
                        $unJson['table_name']);
                    $tmp['created_at']  = $item['created_at'];
                    $tmp['id']          = $item['id'];
                    $result[]           = $tmp;
                }
            }

            return $this->setLayuiJson(0, 'ok', $listArr['total'], $result);
        } else {
            $data = [
                'category'       => TagData::$tagCategory,
                'category_child' => TagData::getCategoryChild(),
            ];
            $auth = $this->getAuth();
            return view('tag.index', compact('data', 'auth'));
        }
    }

    public function getTemp()
    {
        $result = TagData::get();
        foreach ($result as $row) {
            dump($row->toArray());
//            $json = $row['data'];
//            if (json_decode($json)) {
//                $tmp        = json_decode($json, true);
//                $department = array_flip(TagData::$department);
//                if (isset($department[$tmp['defined_department']])) {
//                    $tmp['defined_department'] = $department[trim($tmp['defined_department'])];
//                }
//                $s1 = array_flip(TagData::$tagType);
//                if (isset($s1[$tmp['tag_type']])) {
//                    $tmp['tag_type'] = $s1[$tmp['tag_type']];
//                }
//                $s1 = array_flip(TagData::$tagValueUnit);
//                if (isset($s1[$tmp['tag_unit']])) {
//                    $tmp['tag_unit'] = $s1[$tmp['tag_unit']];
//                }
//                $s1 = array_flip(TagData::$tagState);
//                if (isset($s1[$tmp['tag_state']])) {
//                    $tmp['tag_state'] = $s1[$tmp['tag_state']];
//                }
//                $s1 = array_flip(TagData::$tagPhysicsType);
//                if (isset($s1[$tmp['tag_physics_type']])) {
//                    $tmp['tag_physics_type'] = $s1[$tmp['tag_physics_type']];
//                }
//                $s1 = array_flip(TagData::$tagPhysicsType);
//                if (isset($s1[$tmp['tag_physics_type']])) {
//                    $tmp['tag_physics_type'] = $s1[$tmp['tag_physics_type']];
//                }
//                $s1 = array_flip(TagData::$tagPhysicsType);
//                if (isset($s1[$tmp['tag_physics_type']])) {
//                    $tmp['tag_physics_type'] = $s1[$tmp['tag_physics_type']];
//                }
//                $s1 = array_flip(TagData::$openAuth);
//                if (isset($s1[$tmp['open_auth']])) {
//                    $tmp['open_auth'] = $s1[$tmp['open_auth']];
//                }
//                dump($tmp);
//                if ($this->request->get('flag') == 1) {
//                    $row->data = json_encode($tmp);
//                    dump($row);
//                    if ($this->request->get('tag') == 2) {
//                        $bool = $row->save();
//                        dump($bool);
//                    }
//                }
//            } else {
//                echo '异常数据';
//                if (strpos($json, 'column_name""') !== false) {
//                    $json      = str_replace('column_name""', 'column_name', $json);
//                    $row->data = $json;
//                    $bool      = $row->save();
//                    dump($row);
//                    dump($bool);
//                }
//            }
        }
    }

    /**
     *
     * @return Response|TagController|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function create()
    {
        $id = $this->request->input('id', 0);
        if ($this->isPost()) {
            if (!$this->getAuth()) {
                return $this->setJson(11, '权限不足');
            }
            $params = $this->request->all();
            unset($params['id']);
            if ($params['tag_name'] == '') {
                return $this->setJson(1, '请输入名称');
            }
            $tag = new TagData();
            if ($id > 0) { //edit
                $tag = TagData::find($id);
                if (!$tag) {
                    return $this->setJson(8, 'id异常');
                }
                if ($tag->checkTagNameUnique2($id, $params['tag_name'])) {
                    return $this->setJson(10, '名称已存在,请更改');
                }
            } else {//add
                if ($tag->checkTagNameUnique($params['tag_name'])) {
                    return $this->setJson(10, '名称已存在,请更改');
                }
                $tag->tag_id = $tag->getNextTagId();
            }
            $tag->category_id       = $params['category'];
            $tag->category_child_id = $params['category_child'];
            $tag->tag_name          = $params['tag_name'];
            $tag->data              = json_encode($params);
            $bool                   = $tag->save();
            if ($bool) {
                return $this->setJson(0, $id > 0 ? '编辑成功' : '添加成功');
            }
            return $this->setJson(11, $id > 0 ? '编辑失败' : '添加失败');
        } else {
            $data = [
                'category'       => TagData::$tagCategory,
                'category_child' => TagData::getCategoryChild(),
                'department'     => TagData::$department,
                'tagState'       => TagData::$tagState,
                'openAuth'       => TagData::$openAuth,
                'tagType'        => TagData::$tagType,
                'tagValueUnit'   => TagData::$tagValueUnit,
                'tagPhysicsType' => TagData::$tagPhysicsType,
            ];
            $old  = [];
            if ($id > 0) {
                $item = TagData::find($id);
                if ($item) {
                    $old = json_decode($item['data'], true);
                }
                $title = '编辑标签';
            } else {
                $title = '添加标签';
            }
            $pid = $id;
            return view('tag.add', compact('data', 'pid', 'old', 'title'));
        }
    }

    /**
     * 连动切换不同分类
     * @return Response|TagController
     */
    public function change_category()
    {
        $id   = $this->request->input('id');
        $data = TagData::getCategoryChild($id);
        return $this->setJson(0, 'ok', $data);
    }

    /**
     * @return Response|TagController
     */
    public function destroy()
    {
        $id = $this->request->input('id', 0);
        if ($id <= 0) {
            return $this->setJson(10, 'id异常');
        }
        $item = TagData::where('id', $id)->first();
        if ($item) {
            $bool = $item->delete();
            if ($bool) {
                return $this->setJson(0, '删除成功');
            }
        }
        return $this->setJson(12, '删除失败');
    }
}
